package com.smec.remes.base;

import android.content.Context;

import com.hwangjr.rxbus.Bus;
import com.hwangjr.rxbus.SmecRxBus;
import com.smec.moblie.SMECApplication;
import com.smec.remes.api.SmecRemesService;

import com.smec.remes.smecManager.SmecRetrofit.ApiException;
import com.smec.remes.smecManager.SmecRetrofit.RetrofitServiceManager;
import com.smec.remes.util.NetworkState;

import java.io.Serializable;
import java.util.concurrent.TimeUnit;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

/**
 * Created by Administrator on 2017/11/23.
 */

public class SmecBasePresenter implements Serializable {
    protected SmecRemesService smecPackingService;
    protected Context mContext;
    protected Bus mRxbus;

    public SmecBasePresenter(Context mContext){
        this.mContext = mContext;
        mRxbus= SmecRxBus.get();
        mRxbus.register(this);
        smecPackingService= RetrofitServiceManager.getSmecPackingService();
    }

    /**
     * 调度线程，绑定生命周期，判断有无网络连接
     * @param observable
     * @param <T>
     * @return
     */
    protected <T> Observable<T> schedulerThread(Observable<T> observable){
        return observable.debounce(300, TimeUnit.MILLISECONDS, AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {   //Action0 就是把 onCompleted() 作为参数传入 subscribe() 。
                    //doOnSubscribe操作符跟onStart方法一样，都是在 subscribe() 方法调用后且事件发送之前 执行
                    @Override
                    public void call() {
                        if(!NetworkState.networkConnected(SMECApplication.getContext())){
                            throw new ApiException("","无网络连接");
                        }
                    }
                })
                .subscribeOn(Schedulers.io()) // 指定subscribe()发生在IO线程
                .observeOn(AndroidSchedulers.mainThread()); // 指定Subscriber的回调发生在UI线程
    }

}
